<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>风力等级可视化</title>
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f8f9fa;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            position: relative;
        }

        .controls {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 20px;
            background-color: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .control-group {
            display: flex;
            flex-direction: column;
            margin-right: 20px;
        }

        label {
            margin-bottom: 5px;
            font-weight: bold;
        }

        select {
            padding: 8px;
            border-radius: 4px;
            border: 1px solid #ddd;
            min-width: 150px;
        }

        button {
            padding: 8px 15px;
            background-color: #007BFF;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            align-self: flex-end;
        }

        button:hover {
            background-color: #0056b3;
        }

        .chart-container {
            background-color: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .status {
            margin-top: 10px;
            color: #6c757d;
            font-size: 0.9em;
        }

        .home-btn {
            position: absolute;
            top: 10px;
            right: 10px;
            padding: 8px 15px;
            background-color: #ff4747;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>风力等级季节分布</h1>
        <div class="controls">
            <div class="control-group">
                <label for="city">选择城市</label>
                <select id="city">
                    <option value="">请选择城市</option>
                </select>
            </div>
            <div class="control-group">
                <label for="year">选择年份</label>
                <select id="year">
                    <option value="">请选择年份</option>
                </select>
            </div>
            <button id="update-btn">生成图表</button>
        </div>
        <div class="chart-container">
            <div id="chart" style="width: 100%; height: 500px;"></div>
            <div class="status">
                <span id="status-text">数据更新时间: </span>
            </div>
        </div>
    </div>

    <script>
        // 加载城市和年份选项（使用后端模板变量）
        async function loadOptions() {
            try {
                // 直接从后端渲染的模板中获取初始城市和年份
                const initialCity = '{{ initial_city }}';
                const initialYear = '{{ initial_year }}';

                // 获取城市和年份列表
                const cities = {{ cities | tojson }};
                const years = {{ years | tojson }};

                // 获取下拉框元素
                const citySelect = document.getElementById('city');
                const yearSelect = document.getElementById('year');

                // 清空默认选项
                citySelect.innerHTML = '<option value="">请选择城市</option>';
                yearSelect.innerHTML = '<option value="">请选择年份</option>';

                // 填充城市选项
                cities.forEach((city, index) => {
                    const option = document.createElement('option');
                    option.value = city;
                    option.textContent = city;
                    citySelect.appendChild(option);

                    // 设置默认选中项
                    if (city === initialCity) {
                        option.selected = true;
                    }
                });

                // 填充年份选项（降序排列）
                const sortedYears = [...years].sort((a, b) => b - a);
                sortedYears.forEach((year, index) => {
                    const option = document.createElement('option');
                    option.value = year;
                    option.textContent = year;
                    yearSelect.appendChild(option);

                    // 设置默认选中项
                    if (year === initialYear) {
                        option.selected = true;
                    }
                });

                document.getElementById('status-text').textContent = `数据更新时间: ${new Date().toLocaleString()}`;

                // 自动触发一次图表生成
                updateChart();

            } catch (error) {
                console.error('加载城市/年份失败:', error);
                document.getElementById('chart').innerHTML = `<div style="text-align: center; padding: 50px;">${error.message}</div>`;
                alert('加载城市或年份失败，请刷新页面重试');
            }
        }

        // 生成图表（优化数据处理和显示）
        function generateChart(data) {
            if (!data || data.data.length === 0) {
                document.getElementById('chart').innerHTML = '<div style="text-align: center; padding: 50px;">没有可用数据</div>';
                return;
            }

            const seasons = data.seasons; // 季节名称
            const windData = data.data;    // 风力等级数据
            const traces = [];

            // 确保风力等级按升序排列
            const sortedWindData = [...windData].sort((a, b) => a.风力等级 - b.风力等级);

            // 为每个风力等级创建一个柱状图系列
            sortedWindData.forEach(gradeItem => {
                const grade = gradeItem.风力等级;
                // 按季节顺序获取天数
                const counts = seasons.map(season => gradeItem[season] || 0);

                traces.push({
                    x: seasons,
                    y: counts,
                    name: `风力等级 ${grade}级`,
                    type: 'bar',
                    marker: {
                        color: getWindColor(grade),
                        line: { width: 1, color: 'white' }
                    },
                    opacity: 0.9
                });
            });

            // 计算Y轴最大值，确保图表显示完整
            const maxValue = Math.max(0, ...windData.flatMap(item =>
                Object.values(item).filter(v => typeof v === 'number')));

            // 图表布局配置
            const layout = {
                title: `${data.city} ${data.year}年风力等级季节分布`,
                barmode: 'stack', // 堆叠柱状图
                xaxis: {
                    title: '季节',
                    tickmode: 'array',
                    tickvals: seasons,
                    ticktext: seasons,
                    categoryorder: 'array',
                    categoryarray: seasons
                },
                yaxis: {
                    title: '天数',
                    range: [0, maxValue * 1.1] // 稍微扩大范围，使图表更美观
                },
                legend: {
                    x: 0,
                    y: 1.05,
                    orientation: 'h',
                    traceorder: 'normal'
                },
                margin: { t: 60, b: 60, l: 60, r: 20 },
                hovermode: 'x unified',
                font: { size: 12 }
            };

            // 渲染图表
            const chartDiv = document.getElementById('chart');
            if (chartDiv.children.length > 0) {
                Plotly.react('chart', traces, layout);
            } else {
                Plotly.newPlot('chart', traces, layout);
            }
        }

        // 根据风力等级获取颜色（优化颜色映射）
        function getWindColor(grade) {
            const colors = [
                '#e0f3ff', '#a3d0ff', '#66b0ff', '#2990ff', '#0072e3',   // 1-5级
                '#0056b3', '#003fa3', '#002893', '#001283', '#000073',   // 6-10级
                '#4c0066', '#800059', '#66004d', '#4d0033'              // 11级及以上
            ];
            return grade <= colors.length ? colors[grade - 1] : colors[colors.length - 1];
        }

        // 更新图表（修正API路径和错误处理）
        async function updateChart() {
            const city = document.getElementById('city').value;
            const year = document.getElementById('year').value;

            if (!city || !year) {
                alert('请选择城市和年份');
                return;
            }

            document.getElementById('chart').innerHTML = '';
            document.getElementById('status-text').textContent = '正在加载数据...';

            try {
                // 调用后端API获取风力数据（注意路径与后端蓝图匹配）
                const response = await fetch(`/menu/seasonal_wind_grades?city=${encodeURIComponent(city)}&year=${year}`);

                if (!response.ok) {
                    throw new Error(`服务器错误: ${response.statusText || '获取数据失败'}`);
                }

                const data = await response.json();
                generateChart(data);
                document.getElementById('status-text').textContent = `数据更新时间: ${new Date().toLocaleString()}`;

            } catch (error) {
                document.getElementById('chart').innerHTML = `<div style="text-align: center; padding: 50px;">${error.message}</div>`;
                console.error('更新图表失败:', error);
            }
        }

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', async () => {
            await loadOptions();
            document.getElementById('update-btn').addEventListener('click', updateChart);
            document.getElementById('city').addEventListener('change', updateChart);
            document.getElementById('year').addEventListener('change', updateChart);
        });
    </script>
</body>

</html>